package librecalcdataproxy.ui;

import com.sun.star.beans.XPropertySet;
import com.sun.star.frame.XController;
import com.sun.star.ui.ContextMenuExecuteEvent;
import com.sun.star.ui.ContextMenuInterceptorAction;
import com.sun.star.ui.XContextMenuInterceptor;
import com.sun.star.uno.UnoRuntime;
import librecalcdataproxy.server.EventExchanger;
public class ContextMenuInterceptor implements XContextMenuInterceptor {
    EventExchanger ee;
    
    public ContextMenuInterceptor(EventExchanger ee){
        this.ee = ee;
    }
    public ContextMenuInterceptor(XController controller, EventExchanger ee){
        com.sun.star.ui.XContextMenuInterception xContextMenuInterception =
        ( com.sun.star.ui.XContextMenuInterception ) UnoRuntime.
        queryInterface(com.sun.star.ui.XContextMenuInterception.class, controller);
        
        
        ContextMenuInterceptor aContextMenuInterceptor = new ContextMenuInterceptor(ee) ;
        com.sun.star.ui.XContextMenuInterceptor xContextMenuInterceptor =
        ( com.sun.star.ui.XContextMenuInterceptor )
        UnoRuntime.queryInterface(
        com.sun.star.ui.XContextMenuInterceptor.class,
        aContextMenuInterceptor ) ;
        xContextMenuInterception.registerContextMenuInterceptor(xContextMenuInterceptor ) ;
        
    }

    //TODO: Możliwość modyfikacji etykiety menu kontekstowego (np. dla innych języków niż angielski)
    @Override
    public ContextMenuInterceptorAction notifyContextMenuExecute(ContextMenuExecuteEvent aEvent) {
        
        //W przypadku gdy nie jest oczekiwany eksport danych pozostawiamy niezmienione menu kontekstowe
        if(!this.ee.isWaiting())
            return com.sun.star.ui.ContextMenuInterceptorAction.IGNORED;

        try {

           
            com.sun.star.container.XIndexContainer xContextMenu = aEvent.ActionTriggerContainer;
            com.sun.star.lang.XMultiServiceFactory xMenuElementFactory =
            (com.sun.star.lang.XMultiServiceFactory)UnoRuntime.queryInterface(
            com.sun.star.lang.XMultiServiceFactory.class, xContextMenu );
            if ( xMenuElementFactory != null ) {
                com.sun.star.beans.XPropertySet xRootMenuEntry =
                (XPropertySet)UnoRuntime.queryInterface(
                com.sun.star.beans.XPropertySet.class,
                xMenuElementFactory.createInstance( "com.sun.star.ui.ActionTrigger" ));

                xRootMenuEntry.setPropertyValue( "Text", new String( "Export selected data" ));
                xRootMenuEntry.setPropertyValue( "CommandURL", new String( ".uno:LCDPExport" ));
                xContextMenu.insertByIndex( 0, (Object)xRootMenuEntry );


                return com.sun.star.ui.ContextMenuInterceptorAction.EXECUTE_MODIFIED;
            }
        }
        catch ( Exception ex ) {
            System.out.println(ex.toString());
        }

        return com.sun.star.ui.ContextMenuInterceptorAction.IGNORED;
    }
}